import { setModel, useModel } from "@/stores/models";
import { Canvas } from "@react-three/fiber";
import { lazy, Suspense } from "react";
import { DEBUG, ENV_MAP_A, KEY_MAP, SCENE_A, SCENE_A_PHYSIC } from "@/config";
import {
  AdaptiveDpr,
  Environment,
  Html,
  KeyboardControls,
  Loader,
  Preload,
} from "@react-three/drei";
import { Physics } from "@react-three/rapier";
import Player from "../player";
import Floor from "../floor";
import Effects from "../effects";
import { useDebug, setDebug } from "@/stores/debug";
import { useConfig, ToneMap } from "@/hooks/useConfig";
import Points from "../points";
import PhysicFloor from "../physicFloor";

// 使用懒加载来优化
const DebugPanel = lazy(() => import("../debugPanel"));

export default function Home() {
  const gameStart = useModel((state) => state.gameStart);
  const showCollider = useDebug((state) => state.showCollider);
  const { tone, points1, otherSetting } = useConfig();

  function Loading() {
    return (
      <Html>
        <Loader
          initialState={(active: boolean) => {
            !active &&
              setTimeout(() => {
                setModel({ gameStart: true });
              }, 500);
            return true;
          }}
        />
      </Html>
    );
  }

  return (
    <Canvas
      style={{ width: "100%", height: "100%" }}
      camera={{
        fov: 60,
        near: 0.1,
        far: 1000,
      }}
      onPointerMissed={() => setDebug({ target: null })}
      onCreated={({ gl }) => {
        gl.toneMapping = ToneMap[tone.toneMapping];
        gl.toneMappingExposure = tone.exposure;
      }}
    >
      <Suspense fallback={<Loading />}>
        {/* 优先渲染基础组件 */}
        <color attach="background" args={[0xffffff]} />
        <ambientLight intensity={0.5} />
        <Environment files={ENV_MAP_A} />
        <Floor path={SCENE_A} />
        <Points points={points1} activeDis={otherSetting.activeDis1} />
        {/* 将需要懒加载的组件放在稍后 */}
        <Physics debug={showCollider} timeStep="vary" paused={!gameStart}>
          {!DEBUG && (
            <KeyboardControls map={KEY_MAP}>
              <Player />
            </KeyboardControls>
          )}
          <PhysicFloor path={SCENE_A_PHYSIC} />
        </Physics>
        {DEBUG && <DebugPanel />}
      </Suspense>
      {/* 将这些独立的优化组件放在最后 */}
      <Preload all />
      <AdaptiveDpr pixelated />
      <Effects />
    </Canvas>
  );
}
